<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            v-model="query.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addGoods">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" width="400px">
        </el-table-column>
        <el-table-column prop="goods_price" label="商品价格"> </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量">
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{ parseTime(scope.row.upd_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
              @click="getEdit(scope.row.goods_id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="del(scope.row.goods_id)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑 -->
      <el-dialog title="商品修改" :visible.sync="rolesEditVisible">
        <el-form :model="goods" ref="rolesEditRef" :rules="rolesRules">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="goods.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="goods.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_weight">
            <el-input v-model="goods.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_number">
            <el-input v-model="goods.goods_number"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="rolesEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="edit">确 定</el-button>
        </div>
      </el-dialog>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pagenum"
        :page-sizes="[3, 5, 8, 10]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import Breadcrumb from "@/mixins/mixin.vue";
import { getList, delGoods } from "@/utils/axios/goodsApi";
export default {
  components: { Breadcrumb },
  data() {
    return {
      tableData: [],
      query: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      type: "",
      rolesEditVisible: false,
      // 基本信息
      goods: {
        goods_id: "",
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        pics: [],
        goods_introduce: "",
      },
      goodsEdit:{},
      rolesRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    addGoods() {
      let a = this.$router.getRoutes();
      let index = a.findIndex((item) => {
        return item.path == "/addgoods";
      });
      if (index == -1) {
        let obj = {
          path: "/addgoods",
          name: "addgoods",
          component: () => import("@/components/Addgoods.vue"),
        };
        this.$router.addRoute("Home", obj);
        this.$store.commit("routeModule/addRouter", obj);
      }
      this.$router.push("/addgoods");
    },
    async getList() {
      let { data: res } = await getList(this.query);
      this.tableData = res.data.goods;
      this.total = res.data.total;
    },
    parseTime(time, cFormat) {
      if (arguments.length === 0) {
        return null;
      }
      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
          time = parseInt(time);
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
      };
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
          return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        return value.toString().padStart(2, "0");
      });
      return time_str;
    },
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.query.pagenum = val;
      this.getList();
    },

    async del(id) {
      let { data: res } = await delGoods(id);
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
        this.getList();
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    async getEdit(id) {
      let { data } = await this.$http.get("goods/" + id);
      console.log(data.data);
      this.goods = data.data;
      this.rolesEditVisible = true;
    },


    edit(){
        this.$refs.rolesEditRef.validate(async (flag) => {
        if (!flag) {
          return false;
        }
        //  关闭模态框
        let { data } = await this.$http.put(`goods/${this.goods.goods_id}`,this.goods);
        if (data.meta.status == 200) {
          this.$message.success("商品更新成功");
          this.rolesEditVisible = false;
          this.getList();
        } else {
          this.$message.error('商品更新失败');
        }
      });
    }
    

  },
  mounted() {
    this.getList();
  },
};
</script>